package at.ac.univie.zsu.aguataplan.ui.template;

import java.awt.Component;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;

import com.toedter.calendar.JDateChooser;

/**
 * @author gerry
 * 
 */
public class DatePanel extends JPanel {

	private static final long serialVersionUID = 1L;

	public static final int SIZE_X = 150;
	public static final int SIZE_Y = 25;

	private JDateChooser jDateChooser;
	private SpinnerModel spinnerModel;
	private JSpinner jSpinner;

	// ----------------------------------------------------
	// CONSTRUCTOR
	// ----------------------------------------------------

	public DatePanel(Date value) {

		jDateChooser = new JDateChooser();
		if (value != null) {
			jDateChooser.setDate(value);
		}
		for (Component comp : jDateChooser.getComponents()) {
			if (comp instanceof JTextField) {
				((JTextField) comp).setColumns(50);
				((JTextField) comp).setEditable(false);
			}
		}

		this.add(jDateChooser);

		spinnerModel = new SpinnerDateModel();
		jSpinner = new JSpinner(spinnerModel);
		JComponent editor = new JSpinner.DateEditor(jSpinner, "HH:mm");
		jSpinner.setEditor(editor);
		if (value != null) {
			jSpinner.setValue(value);
		}

		this.add(jSpinner);

		this.setSize(SIZE_X, SIZE_Y);

	}

	// ----------------------------------------------------
	// METHODS
	// ----------------------------------------------------

	/**
	 * get date and time selected by swing component
	 * 
	 * @return
	 */
	public Date getDate() {
		Date date = jDateChooser.getDate();
		Date time = (Date) jSpinner.getValue();

		if (date == null) {
			return new Date();
		}

		Calendar c = Calendar.getInstance();
		Calendar d = Calendar.getInstance();
		d.setTime(date);
		Calendar t = Calendar.getInstance();
		t.setTime(time);

		c.set(d.get(Calendar.YEAR), d.get(Calendar.MONTH), d.get(Calendar.DATE), t.get(Calendar.HOUR_OF_DAY),
				t.get(Calendar.MINUTE), 0);
		return c.getTime();
	}

	public void setDate(Date value) {
		jSpinner.setValue(value);
		jDateChooser.setDate(value);
	}

	public void setDateEnabled(boolean enabled) {
		jDateChooser.setEnabled(enabled);
		jSpinner.setEnabled(enabled);
	}

	public void cleanPanel() {
		jSpinner.setValue(new Date(0));
		jDateChooser.setDate(null);
	}
}
